//
//  WDLoanManagerController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/29.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDLoanManagerController.h"
#import "WDEditOrderController.h"
#import "PushViewController.h"
#import "WDLoanHeadView.h"
#import "WDLoanCell.h"
#import "WDLoan.h"
#import "WDEditLoanController.h"
#import "WDLoanDetailController.h"
#import "WDCover.h"
#import "WDPlaceholderView.h"
#import "WDRightView.h"

typedef void(^succeed)(id responseObject);
typedef void(^filed)(NSError *error);

@interface WDLoanManagerController ()<UITableViewDelegate,UITableViewDataSource, WDRightViewDelegate>
/** 头部视图 */
@property (nonatomic, weak) WDLoanHeadView *loanHeadView;
/** 创建视图 */
@property (nonatomic, strong) UIView *creatView;
/** 创建按钮 */
@property (strong, nonatomic) UIButton *creatBtn;
/** 无结果占位图 */
@property (strong, nonatomic) WDPlaceholderView *NoDataView;
/** 右侧首字母筛选 */
@property (strong, nonatomic) NSString *start_with;

@end

@implementation WDLoanManagerController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WDBackColor;
    
    if ([self respondsToSelector:@selector(clickNavLeft)]) {
        //加载导航条
        [self loadNavItemWithAction:@selector(clickNavLeft) btnImage:@"actionbar" btnSelImage:@"actionbar" title:@"客户贷款"];
    }
    
    //添加这句话，tableView就不会被遮盖
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self loadLoanTableView];
    
    [self loadRightView];
    
    //[self loadHeadView];
    
    if ([WDVerify verifyStr:finance_create inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]]) {
        
        [self loadAddBtn];
        
        [self loadCreatView];
        self.creatBtn.hidden = NO;
        
    } else {
        
        [self loadCreatView];
        self.creatBtn.hidden = YES;
    }
    
    //加载图
    self.placeView = [self loadPlaceViewWithImageName:@"icon_loading" status:@"努力加载中..."];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.page = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@(self.page) forKey:@"current_page"];
    if (self.start_with && ![_start_with isEqualToString:@""]) {
        [parameters setObject:self.start_with forKey:@"start_with"];
    }
    
    [parameters setObject:@(10) forKey:@"limit"];
    [parameters setObject:@(3) forKey:@"ctype"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceList];
    
    [self sendRequestDataWithURLStr:url Model:NSStringFromClass([WDLoan class]) parameters:parameters succeed:^(id responseObject) {
        
        [self hideLoadView];
        
        if (!self.dataArray.count) {
            
            self.creatView.hidden = NO;
        } else {
            self.creatView.hidden = YES;
        }
        
    } filed:nil];
}

#pragma mark - 控件创建

/** 加载贷款条目视图 */
- (void)loadLoanTableView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;
    
    tableView.backgroundColor = WDBackColor;
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    [tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(0);
        make.left.equalTo(10);
        make.right.equalTo(-10);
        make.bottom.equalTo(0);
    }];
    
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.page = 1;
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@(self.page) forKey:@"current_page"];
        if (self.start_with && ![_start_with isEqualToString:@""]) {
            [parameters setObject:self.start_with forKey:@"start_with"];
        }
        
        [parameters setObject:@(10) forKey:@"limit"];
        [parameters setObject:@(3) forKey:@"ctype"];
        
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceList];
        
        [self sendRequestDataWithURLStr:url Model:NSStringFromClass([WDLoan class]) parameters:parameters succeed:^(id responseObject) {
            
        } filed:nil];
    }];
    
    tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@(self.page) forKey:@"current_page"];
        if (self.start_with && ![_start_with isEqualToString:@""]) {
            [parameters setObject:self.start_with forKey:@"start_with"];
        }
        
        [parameters setObject:@(10) forKey:@"limit"];
        [parameters setObject:@(3) forKey:@"ctype"];
        
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceList];
        
        [self sendRequestDataWithURLStr:url Model:NSStringFromClass([WDLoan class]) parameters:parameters succeed:nil filed:nil];
    }];
    
}

/** 右侧检索 */
- (void)loadRightView
{
    WDRightView *rightView = [WDRightView rightView];
    
    rightView.layer.cornerRadius = 10;
    
    rightView.clipsToBounds = YES;
    
    rightView.delegate = self;
    
    [self.view addSubview:rightView];
    
    [rightView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view.centerY);
        make.right.equalTo(-5);
        make.width.equalTo(20);
        make.height.equalTo(WDScale(500));
    }];
}

/** 加载头部视图 */
- (void)loadHeadView
{
    WDLoanHeadView *headView = [WDLoanHeadView loanHeadView];
    [self.view addSubview:headView];
    self.loanHeadView = headView;
    
    [headView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(0);
        make.left.right.equalTo(0);
        make.height.equalTo(44);
    }];
}

/** 添加按钮 */
- (void)loadAddBtn
{
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.backgroundColor = ColorForRGB(0x4a90e2);
    [addBtn setImage:[UIImage imageNamed:@"icon-tianjiazhaopian"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(clickAddBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:addBtn];
    
    [addBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(-30);
        make.width.height.equalTo(61);
    }];
    
    //加阴影效果
    addBtn.layer.cornerRadius = 30.5;
    
    addBtn.layer.shadowOffset = CGSizeMake(1, 1);
    
    addBtn.layer.shadowOpacity = 0.8;
    
    addBtn.layer.shadowColor = [UIColor blackColor].CGColor;
}

/** 新建贷款视图 */
- (void)loadCreatView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = WDBackColor;
    [self.view addSubview:view];
    view.hidden = YES;
    self.creatView = view;
    
    //图标
    UIImageView *iconImage = [[UIImageView alloc] init];
    iconImage.image = [UIImage imageNamed:@"icon_loadFailed"];
    [view addSubview:iconImage];
    [iconImage makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(100);
        make.centerX.equalTo(view.centerX);
        make.height.equalTo(88);
        make.width.equalTo(103);
    }];
    
    //文字
    UILabel *descLabel = [[UILabel alloc] init];
    descLabel.text = @"目前没有贷款申请";
    descLabel.textColor = ColorForRGB(0xaaaaaa);
    descLabel.font = [UIFont systemFontOfSize:15];
    descLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:descLabel];
    [descLabel makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImage.bottom).offset(15);
        make.centerX.equalTo(view.centerX);
    }];
    
    //创建按钮
    UIButton *createBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    createBtn.backgroundColor = WDNavSeleColor;
    [createBtn setTitle:@"马上创建" forState:UIControlStateNormal];
    createBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    createBtn.layer.cornerRadius = 4;
    createBtn.clipsToBounds = YES;
    [createBtn setTitleColor:ColorForRGB(0xffffff) forState:UIControlStateNormal];
    [createBtn addTarget:self action:@selector(createClick) forControlEvents:UIControlEventTouchUpInside];
    self.creatBtn = createBtn;
    [view addSubview:createBtn];
    [createBtn makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(descLabel.bottom).offset(26.5);
        make.width.equalTo(100);
    }];
    
}

#pragma mark - 按钮点击
- (void)createClick
{
    
    WDEditOrderController *tempV = [[UIStoryboard storyboardWithName:NSStringFromClass([WDEditOrderController class]) bundle:nil] instantiateViewControllerWithIdentifier:@"WDEditOrderController"];
    
    tempV.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempV animated:YES];
    
}

- (void)clickAddBtn
{
    WDEditOrderController *tempV = [[UIStoryboard storyboardWithName:NSStringFromClass([WDEditOrderController class]) bundle:nil] instantiateViewControllerWithIdentifier:@"WDEditOrderController"];
    
    tempV.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempV animated:YES];
}

#pragma mark - 请求接口
//删除未上传
- (void)deleteFinanceWithFileId:(NSString *)fileId success:(succeed)success failed:(filed)filed
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceDel];
    
    NSDictionary *parameters = @{
                                @"finance_id":fileId,
                                 @"ctype":@3
                                 };
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil
         progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             
             if (success) {
                 success(responseObject);
             }
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
             if (error) {
                 
                 filed(error);
             }
             
         }];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDLoanCell *cell = [WDLoanCell loanCellWithTableView:tableView];
    
    cell.loanData = self.dataArray[indexPath.section];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 135;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //跳转贷款详情(根据状态跳转相应的页面)
    WDLoan *loan = self.dataArray[indexPath.section];
    
    if ([loan.status intValue] == WDLoanTypeNotUpload) {//未上传
        WDEditLoanController *tempV = [[WDEditLoanController alloc] init];
        
        tempV.loan = loan;
        
        tempV.view.backgroundColor = WDBackColor;
        
        [self.navigationController pushViewController:tempV animated:YES];
    } else if ([loan.status intValue] == WDLoanTypeDelay || [loan.status intValue] == WDLoanTypeNotPass || [loan.status intValue] == WDLoanTypeIDNotPass) {
        WDLoanDetailController *tempVC = [[WDLoanDetailController alloc] init];
        tempVC.loan = loan;
        tempVC.hiddenBtn = NO;
        tempVC.view.backgroundColor = WDBackColor;
        
        [self.navigationController pushViewController:tempVC animated:YES];
    } else {
        WDLoanDetailController *tempVC = [[WDLoanDetailController alloc] init];
        tempVC.loan = loan;
        tempVC.hiddenBtn = YES;
        tempVC.view.backgroundColor = WDBackColor;
        
        [self.navigationController pushViewController:tempVC animated:YES];
    }
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDLoan *loan = self.dataArray[indexPath.section];
    
    if ([loan.status integerValue] == WDLoanTypeNotUpload) {
        return YES;
    } else {
        return NO;
    }
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        WDLoan *tempLoan = self.dataArray[indexPath.section];
        
        [self deleteFinanceWithFileId:tempLoan.id success:^(id responseObject) {
            
            [self.dataArray removeObjectAtIndex:indexPath.section];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop];
            
        } failed:^(NSError *error) {
            
        }];
        
        
    }
    
    [self.tableView reloadData];
}

#pragma mark - WDRightViewDelegate
- (void)rightView:(WDRightView *)right clickStr:(NSString *)str
{
    if (![str isEqualToString:@"全\n部"]) {
        
        self.start_with = str;
    } else {
        self.start_with = nil;
    }
    
    self.page = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@(self.page) forKey:@"current_page"];
    if (self.start_with && ![_start_with isEqualToString:@""]) {
        [parameters setObject:self.start_with forKey:@"start_with"];
    }
    
    [parameters setObject:@(10) forKey:@"limit"];
    [parameters setObject:@(3) forKey:@"ctype"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceList];
    
    [self sendRequestDataWithURLStr:url Model:NSStringFromClass([WDLoan class]) parameters:parameters succeed:^(id responseObject) {
        
        if (![responseObject[@"data"] count]) {
            
            [self showPlaceViewWithImageName:@"icon_loadFailed" status:@"该筛选条件下无结果"];
        } else {
            
            [self hideLoadView];
        }
        
        [self.tableView reloadData];
        
    } filed:nil];
}

@end
